package com.uzai.console.service.wechatprivate.impl;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.constant.Const;
import com.uzai.console.dto.feign.deviceauth.MobileDeviceAuthAdd;
import com.uzai.console.dto.feign.deviceauth.MobileDeviceAuthDel;
import com.uzai.console.dto.feign.uzaimanage.CdkeyMobileQueryDto;
import com.uzai.console.entity.CdkeysMobileApp;
import com.uzai.console.mapper.CdkeysMobileAppMapper;
import com.uzai.console.mapper.DeviceWechatInfoMapper;
import com.uzai.console.para.DeviceMobileSofyAuthRemoteApiPara;
import com.uzai.console.service.feign.ClientApiService;
import com.uzai.console.service.feign.UzaiManageFeignService;
import com.uzai.console.service.remoteapi.DeviceRemoteApiService;
import com.uzai.console.service.wechatprivate.DeviceWechatInfoSyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * 个人微信-微信通讯录
 *
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class DeviceWechatInfoSyncServiceImpl implements DeviceWechatInfoSyncService {

    Logger logger = LoggerFactory.getLogger(DeviceWechatInfoSyncServiceImpl.class);

    @Autowired
    private DeviceRemoteApiService deviceRemoteApiService;
    @Autowired
    private CdkeysMobileAppMapper cdkeysMobileAppMapper;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private UzaiManageFeignService uzaiManageFeignService;
    @Autowired
    private ClientApiService clientApiService;

    /**
     * 添加机器人移动端安装软件授权
     *
     * @param deviceId
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Async("taskExecutor")
    @Override
    public void deviceMobileAuthSync(Long merId, String deviceId, String tradeno, Integer expiredTime, Integer deviceTypeId) {
        try {

            logger.info("----进入机器人移动端安装软件授权方法中----");

            if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(tradeno) || merId == null) {
                return;
            }

            //不包含此设备端，则不授权
            if (!Lists.newArrayList(DeviceTypeEnum.DT_ANDROID_WECHAT_VALUE, DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE).contains(deviceTypeId)) {
                return;
            }

            Integer now = DateUtil.getNowTime();
            //1-查询该设备微信id是否已经授权，如果存在，则需要将最新的过期刷新该授权
            CdkeysMobileApp cdkeysMobileApp = cdkeysMobileAppMapper.selectByDeviceId(deviceId);
            //不存在，查询库存中授权已经到期的卡，进行修改操作
            if (cdkeysMobileApp == null) {
                cdkeysMobileApp = cdkeysMobileAppMapper.selectExpiredCard(now);
            }

            //还不存在，则查询出一张库存卡
            if (cdkeysMobileApp == null) {
                cdkeysMobileApp = cdkeysMobileAppMapper.selectStockCard();
            }

            //最后还不存在，则调用微服务回收未使用卡密接口
            if (cdkeysMobileApp == null) {
                UzaiRespVo<Object> objectUzaiRespVo = uzaiManageFeignService.cdkeyMobileUpdateListByCache(new CdkeyMobileQueryDto());
                logger.info("---调用回收未使用卡密接口微服务--result={}", JSONObject.toJSONString(objectUzaiRespVo));
            }

            if (cdkeysMobileApp != null) {
                DeviceMobileSofyAuthRemoteApiPara deviceMobileAuthRemoteApiPara = new DeviceMobileSofyAuthRemoteApiPara();
                deviceMobileAuthRemoteApiPara.setImei(deviceId);
                deviceMobileAuthRemoteApiPara.setRegCode(cdkeysMobileApp.getCard());
                deviceMobileAuthRemoteApiPara.setExpireTime(expiredTime);
                //发送授权
                if (deviceMobileAuthRemoteApiPara != null && StringUtils.isNotBlank(deviceMobileAuthRemoteApiPara.getRegCode())) {
                    Boolean flag = deviceRemoteApiService.deviceMobileSoftAuth(deviceMobileAuthRemoteApiPara, deviceTypeId);
                    if (flag) {
                        if (cdkeysMobileApp != null) {
                            cdkeysMobileApp.setDeviceId(deviceId);
                            cdkeysMobileApp.setExpireTime(expiredTime);
                            cdkeysMobileApp.setMerId(merId);
                            cdkeysMobileApp.setStatus(1); //已使用
                            cdkeysMobileApp.setUseTime(now);
                            cdkeysMobileApp.setTradeno(tradeno);
                            cdkeysMobileApp.setUpdateTime(now);
                            cdkeysMobileAppMapper.updateById(cdkeysMobileApp);
                        }
                    } else {
                        if (cdkeysMobileApp != null) {
                            cdkeysMobileApp.setDeviceId(null);
                            cdkeysMobileApp.setExpireTime(null);
                            cdkeysMobileApp.setMerId(null);
                            cdkeysMobileApp.setStatus(2); //有问题的卡
                            cdkeysMobileApp.setUseTime(null);
                            cdkeysMobileApp.setTradeno(null);
                            cdkeysMobileApp.setUpdateTime(now);
                            cdkeysMobileAppMapper.updateById(cdkeysMobileApp);
                            //递归循环会造内存溢出
                            //deviceMobileAuthSync(merId, deviceId, tradeno, expiredTime);
                        }
                    }
                } else {
                    return;
                }
            } else {
                return;
            }
        } catch (Exception e) {
            logger.error("-------deviceMobileAuthSync is error; deviceId={}, errorinfo={}", deviceId, e.getMessage());
        }
    }

    /**
     * 给新增加得机器人发送试用卡密
     *
     * @param deviceId
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Async("taskExecutor")
    public void deviceMobileAuthFreeSync(String deviceId, Integer expiredTime, Integer deviceTypeId) {
        DeviceMobileSofyAuthRemoteApiPara deviceMobileAuthRemoteApiPara = new DeviceMobileSofyAuthRemoteApiPara();
        deviceMobileAuthRemoteApiPara.setImei(deviceId);
        deviceMobileAuthRemoteApiPara.setRegCode(Const.Device.REGCODE_FREE);
        deviceMobileAuthRemoteApiPara.setExpireTime(expiredTime);
        deviceRemoteApiService.deviceMobileSoftAuth(deviceMobileAuthRemoteApiPara, deviceTypeId);
    }

    /**
     * 添加机器人移动端安装软件授权
     *
     * @param deviceId
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Async("taskExecutor")
    @Override
    public void mobiledeviceAuthAddSync(String deviceId, Integer deviceTypeId) {

        if (StringUtils.isBlank(deviceId)) {
            return;
        }

        //不包含此设备端，则不授权
        if (!Lists.newArrayList(DeviceTypeEnum.DT_ANDROID_WECHAT_VALUE, DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE).contains(deviceTypeId)) {
            return;
        }

        //添加该机器人的授权
        MobileDeviceAuthAdd mobileDeviceAuthAdd = new MobileDeviceAuthAdd();
        mobileDeviceAuthAdd.setDeviceId(deviceId);
        UzaiRespVo<Object> uzaiRespVo_add = clientApiService.mobileDeviceAuthAdd(mobileDeviceAuthAdd);
        logger.info("调用添加移动端机器人授权接口，dto={}, result={}", JSONObject.toJSONString(mobileDeviceAuthAdd), JSONObject.toJSONString(uzaiRespVo_add));
    }

    /**
     * 删除机器人移动端安装软件授权
     *
     * @param deviceId
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Async("taskExecutor")
    @Override
    public void mobiledeviceAuthDelSync(String deviceId) {
        //添加该机器人的授权
        MobileDeviceAuthDel mobileDeviceAuthDel = new MobileDeviceAuthDel();
        mobileDeviceAuthDel.setDeviceId(deviceId);
        UzaiRespVo<Object> uzaiRespVo_del = clientApiService.mobileDeviceAuthDel(mobileDeviceAuthDel);
        logger.info("调用删除移动端机器人授权接口，dto={}, result={}", JSONObject.toJSONString(mobileDeviceAuthDel), JSONObject.toJSONString(uzaiRespVo_del));
    }


}
